package handlers

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gorilla/mux"
	
	"skedule-backend/database"
	"skedule-backend/utils"
)

// LogHandler 日志处理器
type LogHandler struct{}

// NewLogHandler 创建日志处理器
func NewLogHandler() *LogHandler {
	return &LogHandler{}
}

// LogsResponse 日志响应
type LogsResponse struct {
	Logs  []database.TaskLog `json:"logs"`
	Total int64              `json:"total"`
}

// GetLogs 获取执行日志
func (h *LogHandler) GetLogs(w http.ResponseWriter, r *http.Request) {
	query := database.DB.Model(&database.TaskLog{})

	// 解析查询参数
	params := r.URL.Query()

	// 按任务ID筛选
	if taskID := params.Get("taskId"); taskID != "" {
		query = query.Where("task_id = ?", taskID)
	}

	// 按状态筛选
	if status := params.Get("status"); status != "" {
		query = query.Where("status = ?", status)
	}

	// 按时间范围筛选
	if startDate := params.Get("startDate"); startDate != "" {
		if t, err := time.Parse("2006-01-02", startDate); err == nil {
			query = query.Where("start_time >= ?", t)
		}
	}

	if endDate := params.Get("endDate"); endDate != "" {
		if t, err := time.Parse("2006-01-02", endDate); err == nil {
			// 结束日期加1天，包含当天的所有记录
			endTime := t.AddDate(0, 0, 1)
			query = query.Where("start_time < ?", endTime)
		}
	}

	// 获取总数
	var total int64
	query.Count(&total)

	// 分页参数
	page := 1
	pageSize := 20

	if p := params.Get("page"); p != "" {
		if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
			page = parsed
		}
	}

	if ps := params.Get("pageSize"); ps != "" {
		if parsed, err := strconv.Atoi(ps); err == nil && parsed > 0 && parsed <= 100 {
			pageSize = parsed
		}
	}

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 查询日志
	var logs []database.TaskLog
	if err := query.Order("start_time DESC").
		Offset(offset).
		Limit(pageSize).
		Find(&logs).Error; err != nil {
		Error(w, CodeDatabaseError, utils.T("logs.get.failed"))
		return
	}

	response := LogsResponse{
		Logs:  logs,
		Total: total,
	}

	Success(w, response)
}

// GetTaskLogs 获取特定任务的日志
func (h *LogHandler) GetTaskLogs(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	taskID := vars["taskId"]

	var logs []database.TaskLog
	if err := database.DB.Where("task_id = ?", taskID).
		Order("start_time DESC").
		Limit(50).
		Find(&logs).Error; err != nil {
		Error(w, CodeDatabaseError, utils.T("logs.task.get.failed"))
		return
	}

	Success(w, logs)
}

// DeleteOldLogs 删除过期日志
func (h *LogHandler) DeleteOldLogs(w http.ResponseWriter, r *http.Request) {
	// 获取系统设置
	var settings database.Settings
	database.DB.First(&settings)

	cutoff := time.Now().AddDate(0, 0, -settings.LogRetentionDays)

	result := database.DB.Where("created_at < ?", cutoff).Delete(&database.TaskLog{})
	if result.Error != nil {
		Error(w, CodeDatabaseError, utils.T("logs.cleanup.failed"))
		return
	}

	response := map[string]interface{}{
		"deleted": result.RowsAffected,
		"cutoff":  cutoff,
	}

	SuccessWithMsg(w, utils.T("logs.cleanup.success"), response)
}

// SetupLogRoutes 设置日志路由
func SetupLogRoutes(router *mux.Router, logHandler *LogHandler) {
	logRouter := router.PathPrefix("/logs").Subrouter()
	logRouter.HandleFunc("", logHandler.GetLogs).Methods("GET")
	logRouter.HandleFunc("/tasks/{taskId}", logHandler.GetTaskLogs).Methods("GET")
	logRouter.HandleFunc("/cleanup", logHandler.DeleteOldLogs).Methods("POST")
} 